package com.ct;


import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSONUtil;
import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTHeader;
import cn.hutool.jwt.JWTUtil;
import cn.hutool.jwt.JWTValidator;
import cn.hutool.jwt.signers.JWTSigner;
import cn.hutool.jwt.signers.JWTSignerUtil;
import cn.hutool.log.StaticLog;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@SpringBootTest
public class JwtDemo {

    //创建token
    @Test
    public void cjToken() {
        // 密钥
        byte[] key = "1234567890".getBytes();

        // 设置 JWT 的过期时间（当前时间 + 1小时）
        Date expireDate = new Date(System.currentTimeMillis() + 3600 * 1000);

        // 构建 JWT Token，包含用户信息和过期时间
        String token = JWT.create()
                .setPayload("username", "张三")
                .setPayload("role", "admin")
                .setExpiresAt(expireDate)
                .setKey(key)
                .sign();
//eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VybmFtZSI6IuW8oOS4iSIsInJvbGUiOiJhZG1pbiIsImV4cCI6MTc0NTQ5MjIxM30.v7CyfBf3C7JR3scntJkLm73ZGjc0H7nFhY21lcOv3-0
        StaticLog.info("生成的Token: " + token);
    }

    //解析token
    @Test
    public void jxToken() {
        String rightToken = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VybmFtZSI6IuW8oOS4iSIsInJvbGUiOiJhZG1pbiIsImV4cCI6MTc0NTQ5MjIxM30.v7CyfBf3C7JR3scntJkLm73ZGjc0H7nFhY21lcOv3-0";

        JWT jwt = JWT.of(rightToken);
        StaticLog.info("解析的jwt: " + jwt);
        StaticLog.info("声明类型，一般为jwt-getHeader-type: " + (jwt.getHeader(JWTHeader.TYPE)));
        StaticLog.info("加密算法-alg: " + (jwt.getHeader(JWTHeader.ALGORITHM)));
        StaticLog.info("解析的jwt: " + (jwt.getPayload("sub")));
        StaticLog.info("解析的jwt: " + (jwt.getPayload("username")));
        StaticLog.info("解析的jwt: " + (jwt.getPayload("role")));
    }

    //验证token
    @Test
    public void yzToken(){
        String rightToken = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VybmFtZSI6IuW8oOS4iSIsInJvbGUiOiJhZG1pbiIsImV4cCI6MTc0NTQ5MjIxM30.v7CyfBf3C7JR3scntJkLm73ZGjc0H7nFhY21lcOv3-0";
        // 密钥
        byte[] key = "1234567890".getBytes();
        // 默认验证HS256的算法
        boolean verify = JWT.of(rightToken).setKey(key).verify();
        StaticLog.info("verify->{}",verify);
    }

    //详细验证token
    @Test
    public void xxyzToken(){
        String token = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VybmFtZSI6IuW8oOS4iSIsInJvbGUiOiJhZG1pbiIsImV4cCI6MTc0NTU0OTI5M30.YxCfslQ5EspzBkPln8MYsZLdmFmRhZCiyT41e1r6Dd0\n";

        byte[] key = "1234567890".getBytes();
        // 容忍时间，0秒
        boolean validate = JWT.of(token).setKey(key).validate(0);
        StaticLog.info("verify->{}",validate);
    }

    @Test
    public void cjToken1() {
        Map<String, Object> map = new HashMap<String, Object>() {
            private static final long serialVersionUID = 1L;
            {
                put("uid", Integer.parseInt("123"));
                put("expire_time", System.currentTimeMillis() + 1000 * 60 * 60);
            }
        };

         String token = JWTUtil.createToken(map, "1234".getBytes());
         // eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1aWQiOjEyMywiZXhwaXJlX3RpbWUiOjE3NDY4NDE5OTAxMTV9.V_m3vHSoDDtfsPrSBv_oyT13nRZfvR1Ptd9ExrVnTRI
         StaticLog.info("token->{}",token);
    }

    @Test
    public void jxToken1() {
        String rightToken = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1aWQiOjEyMywiZXhwaXJlX3RpbWUiOjE3NDY4NDE5OTAxMTV9.V_m3vHSoDDtfsPrSBv_oyT13nRZfvR1Ptd9ExrVnTRI";
        final JWT jwt = JWTUtil.parseToken(rightToken);

        StaticLog.info("jwt->{}",jwt.getHeader(JWTHeader.TYPE));
        StaticLog.info("sub->{}",jwt.getPayload("sub"));
        StaticLog.info("uid->{}",jwt.getPayload("uid"));
        StaticLog.info("expire_time->{}",jwt.getPayload("expire_time"));

    }

    //验证token
    @Test
    public void yzToken1(){
        String rightToken = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1aWQiOjEyMywiZXhwaXJlX3RpbWUiOjE3NDU1NTI3ODUyNDZ9.OyZo7mJJMZ9SjxJcPxTrlHYQRE-hJMp1nIjd7qZH5Fs";

        boolean verify = JWTUtil.verify(rightToken, "1234".getBytes());
        StaticLog.info("verify->{}",verify);
    }

    // 生成 JWT
    @Test
    public void createToken() {
        // 设置时间点
        Date issuedAt = new Date();                               // 签发时间
        Date notBefore = new Date();                               // 生效时间
        Date expiresAt = DateUtil.offsetMinute(new Date(), 1);     // 过期时间：30分钟后

        Map<String, Object> payload = new HashMap<>();
        payload.put("userId", "11");
        payload.put(JWT.JWT_ID, "jwt-" + "11");            // JWT ID
        payload.put(JWT.ISSUED_AT, issuedAt);                // 签发时间
        payload.put(JWT.NOT_BEFORE, notBefore);              // 生效时间
        payload.put(JWT.EXPIRES_AT, expiresAt);              // 过期时间

        String token =  JWTUtil.createToken(payload,"1234".getBytes());
        StaticLog.info("token->{}",token);
    }

    // 验证 JWT
    @Test
    public  void verifyToken() {
        String token="eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJuYmYiOjE3NDU1NTA4NDIsImV4cCI6MTc0NTU1MDkwMiwidXNlcklkIjoiMTEiLCJpYXQiOjE3NDU1NTA4NDIsImp0aSI6Imp3dC0xMSJ9.BuWBSfqbxJ_WvL5SplrnE-td-wn4RgqvURlc9LDUD8Y";
         boolean validate = JWTUtil.parseToken(token).setKey("1234".getBytes()).validate(0);


        if (!validate) {
            System.out.println("Token 无效或已过期！");

        }else {
            System.out.println("Token 有效");
        }

        // 打印载荷
        System.out.println("Payload: " + JWTUtil.parseToken(token).getPayloads());

    }


}
